import React from 'react';
import {Tools, Tabs, List,ActivityIndicator,Popover} from 'weaver-mobile';
import { Browser, CKRichText } from 'weaver-mobile-page';
import {RouteLayout, Form,} from 'weaver-mobile-page';
import {observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Route, withRouter} from 'react-router-dom';
import Share from './Share';
import {Icon} from 'weaver-mobile';
import FloatButton from '../../util/FloatButton';
// import RichText from '../../util/richText';

const getLabel = Tools.getLabel;
const ButtonGroup = RouteLayout.ButtonGroup;
const fileTypeList = ",pdf,jpg,jpeg,png,gif,bmp,doc,docx,xls,xlsx,";

@withRouter
@observer
class Add extends React.Component {
  
  componentDidMount() {
    const {store, location} = this.props;
    const {search} = location;
    let query = {};
    if(search && search.indexOf("?") >=0){
    	let params = search.substring(search.indexOf("?")+1);
    	params.split("&").forEach((param)=>{
    		if(param.indexOf("=") >=0){
    			query[param.split("=")[0]] = param.split("=")[1];
    		}
    	})
    }
    const isOffice = query.isOffice ? query.isOffice : "0";
    const mFileType = query.mFileType ? query.mFileType : ".html";
    const docid = query.id ? query.id : 0;
    
    if(docid){
    	const fileid = query.imagefileid ? query.imagefileid : 0;
    	store.initEdit(docid,fileid);
    }else{
	    store.setIsOffice(isOffice);
	    store.setFileType(mFileType);
	    store.init();
	    this.props.history.push(`/add/39/secCategoryBrowser`);
    }
    
  }
  // 考虑到分享页面下回退不应该回到新增页面，share和add还是在一个路由下好
  render() {
    const {store} = this.props, {pageType} = store;
    return (
      <RouteLayout>
        {
          store.loading ? this.getLoadingPage() ://加载中
          pageType === 'edit' ? this.getEditPage() : //编辑页面
          pageType === 'choose' ? this.getChooseCategory() ://选择目录界面
          pageType === 'text' ? this.getTextPage(): //文本界面
          pageType === 'init' ? <div></div> :   //空白页
          <Share key="share-page" store={store}/>//分享界面
        }
      </RouteLayout>
    );
  }
  getEditPage = () => {
  	const {store} = this.props, {canEdit,id,fileid,mFileType} = store;
  	return (
  		<div className="wea-system-doc-whitebg wm-route-layout">
			{!canEdit ?
			<div className="wea-doc-error">
				 <Icon type="wuquanxian" size="lg" style={{width: 100, height: 100}}/>
          		 <div>{getLabel(2012, "对不起，您暂时没有权限！")}</div>
			</div>
			:
			<div style={{height: '100%'}}>
				<div className="wea-system-doc-edit-page">
			        <div style={{height: '100%'}}>
			          <iframe id="webOffice" src={`/docs/e9/weboffice_wps.jsp?isMobile=1&id=`+id+`&fileid=`+fileid+`&isEdit=1&mFileType=` + mFileType} 
			          	frameBorder="0" style={{height: '100%', width: '100%'}}></iframe>
			        </div>
				</div>	
				<ButtonGroup data={[
		          {
		            key: 'submit',
		            text: getLabel(725, "提交"),
		            onClick: () => {
		            	store.saveEdit({history: this.props.history})
		            },
		            type: 'primary',
		          }]}/>		
			</div>
			}
		</div>
  	)
  }
  getLoadingPage = () =>{
    return(
      <div className="wea-doc-whitebg wm-route-layout">
          <div className="wea-doc-error">
            <ActivityIndicator size="large"/>
          </div>
        </div>
    )
  }
  toCreatePage = (id) =>{
    const {store} = this.props;
    store.initSecCategory(id);
  }
  getChooseCategory = () =>{
    const {store} = this.props, {canCreate} = store;
    return(
      <div className="wea-choose-category-bg wm-route-layout">
        <Browser
            label={getLabel(19214, '选择目录')}
            store={store.secCategoryBrowser}
            hasAdvanceSerach
            type={'doccategory'}
            dataParams={{filtertype:store.filtertype,filtercategoryid:store.filterCategoryIdList,iscreate:"1",noAllDirName:'1'}}
            onChange={(value)=>this.toCreatePage(value)}
        />
        {!canCreate &&
        <div className="wea-doc-error">
          <Icon type="wuquanxian" size="lg" style={{width: 100, height: 100}}/>
          <div>{getLabel(390465, "您没有权限在该目录下新建，请重新选择")}</div>
        </div>
        }
      </div>
    )
  }
  
  selectMenuElli = (item,index) =>{
  	const {store} = this.props, {setMenuElliVisible,setIsOffice,setFileType} = store;
  	if(item.key==="BTN_CREATE_DOC_DOCX"){
  		setFileType(".docx");
  		setIsOffice("1");
  	}else if(item.key==="BTN_CREATE_DOC_XLSX"){
  		setFileType(".xlsx");
  		setIsOffice("1");
  	}else if(item.key==="BTN_CREATE_DOC_HTML"){
  		setFileType(".html");
  		setIsOffice("0");
  	}
  	setMenuElliVisible(false);
  }
  
  getPopOver = (menus,mFileType) => {
  	let pops = [];
  	menus.map((menu) => {
  		if((menu.type === "BTN_CREATE_DOC_DOCX" && mFileType != ".docx" && mFileType != ".doc")
  			|| (menu.type === "BTN_CREATE_DOC_XLSX" && mFileType != ".xlsx" && mFileType != ".xls")
  			|| (menu.type === "BTN_CREATE_DOC_HTML" && mFileType != ".html" && mFileType != "")
  		)
  		pops.push(<Popover.Item  key={menu.type}>{menu.menuName}</Popover.Item>);
  	})
  	return pops;
  }
  
  getTextPage = () => {
    const {store} = this.props, {addTab,MenuElliVisible,setMenuElliVisible,
    	hasMenuElli,menus,mFileType,isOffice} = store;
    return (
      <div className="wea-system-doc-whitebg wm-route-layout" key="add-page">
      	{
      	hasMenuElli &&
      	<div className="wea-system-doc-doctype" 
      		style={{position: "absolute",top: "12px",right: "15px",zIndex: 1000}}>
        	<Popover
            key="docdetail-menu-popover"
            align={{offset:[12,0]}}
            placement="bottomRight"
            visible={MenuElliVisible}
            overlay={this.getPopOver(menus,mFileType)}
            onVisibleChange={setMenuElliVisible}
            onSelect={this.selectMenuElli}
          >
            <span className="doc-title-icon">
              <Icon type="ellipsis" size="xs"/>
            </span>
          </Popover>
        </div>
      	}
      	
        <Tabs
          tabs={[
            {title: getLabel(16228, '文档内容'), key: 'content'},
            {title: getLabel(33197, '文档属性'), key: 'property'}
          ]}
          page={addTab}
          onTabClick={(tab, index) => { store.changeTab(tab) }}
          renderTabBar={props => <Tabs.ExpandTabBar {...props} fix={10}   />}
        >
        </Tabs>
        {this.getTabContent(addTab)}
        <ButtonGroup data={[
          {
            key: 'clear',
            text: getLabel(220, "草稿"),
            onClick: () => {
            	isOffice == "1" ?
            	store.saveOffice({isDraft: true, history: this.props.history})
            	:
            	store.save({isDraft: true, history: this.props.history})}
          },
          {
            key: 'submit',
            text: getLabel(725, "提交"),
            onClick: () => {
            	isOffice == "1" ?
            	store.saveOffice({history: this.props.history})
            	:
            	store.save({history: this.props.history})
            },
            type: 'primary',
          }]}/>
      </div>
    );
  }

  //将上传的富文本图片等比例缩小
  uploadImg = () =>{
    let textImg = document.getElementsByTagName("img");
    if(textImg){
      for(let i = 0;i<textImg.length; i++){
        textImg[i].style.maxWidth = '100%';
      }
    }
  }
  uploadFileChange=(key, datas)=>{
    const {store} = this.props;
     let mainfileExit = false;
     let nextmainfileid = "";//记录主附件的下一个支持设置主附件的附件id
     datas && datas.forEach(val=>{
       if(val.id == store.mainimagefile){
         mainfileExit = true;
       }
       if(store.mainimagefile && val.id>store.mainimagefile && !nextmainfileid && fileTypeList.indexOf(","+val.fileExtendName.toLowerCase()+",")>=0){
         nextmainfileid = val.id;
       }
     });
     if(!mainfileExit){
      store.setDatas({"mainimagefile":nextmainfileid});
     }
  }
  setMainfile =(item)=>{
    const {store} = this.props, { mainimagefile} = store;
    if(fileTypeList.indexOf(","+item.fileExtendName.toLowerCase()+",")>=0 && !store.mainimagefile){
      store.setDatas({"mainimagefile":item.id});
     }
    return (<span>{item.filesize}&nbsp;&nbsp;{(store.mainimagefile==item.id) ? '主附件' : ''}</span>);
  }
  getTabContent = (tab) => {
    const {store} = this.props, {/*text, reply,*/ richTextStore,isOffice,mFileType} = store;
    let params = toJS(store.form.formData), {seccategory} = params;
    let secCategoryId = seccategory && Array.isArray(seccategory.value) && seccategory.value.length > 0 ? seccategory.value[0].id : '';
    return (
      <div className="wea-system-doc-add-page">
        <div style={{height: '100%', display: tab === 'content' ? 'block' : 'none'}}>
          {isOffice == "1" ?
          <iframe id="webOffice" src={`/docs/e9/weboffice_wps.jsp?isMobile=1&isEdit=1&mFileType=` + mFileType} 
          	frameBorder="0" style={{height: '100%', width: '100%'}}></iframe>
          :
          <CKRichText
            store={richTextStore}
            onChange={()=>this.uploadImg()}
            replyProps={{
              onUploadChange: (key, datas) => this.uploadFileChange(key, datas),
              onBrowserChange:this.appendBrowser,
              attachmentUploadPropsMap:{ // attachmentUploadPropsMap 自定义上传后面板中的传参，通过配置的key区分
                file: { // file: 是store中注册的上传的key, 这里可以复写AttachmentUpload组件中的参数
                  addActionButtons: item => fileTypeList.indexOf(","+item.fileExtendName.toLowerCase()+",")>=0? [
                    {
                      text: '标记为主附件',
                      className: 'create-doc-mainfile-bg-blue',
                      onPress: () => {
                        const { attach, setAttach } = richTextStore.replyStore;
                        // 1、取值
                        const attachData = toJS(attach).file;
                        const curData = attachData.map(v => (v.id === item.id ? { ...v, isMain: true } : { ...v,isMain: false }));
                        store.setDatas({"mainimagefile":item.id});
                        // 2、改值 - 按照自己的需求更新当前key对应的files
                        setAttach('file', curData);
                      },
                    },
                  ]:[],
                  renderBrief: item => this.setMainfile(item),
                },
              }
            }}
          />
          }
        </div>
        <Form style={{ height: '100%', display: tab === 'content' ? 'none' : 'block' }} key={secCategoryId ? secCategoryId : 'nosec'} store={store.form}>
          <List>
            {this.getFields()}
          </List>
        </Form>
      </div>
    );
  }

  getFields = () => {
    const {store} = this.props,
      { form } = store;
    let { conditioninfo, isInit } = form;
    conditioninfo = toJS(conditioninfo);
    const fields = [];
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          // 摘要只在发布类型为2时显示
          if (field.domkey[0] === 'docmain' && form.formData.docPublishType && form.formData.docPublishType.value !== '2') {
            return;
          }
          if (!field.show) {
            return;
          }
          fields.push(<Form.Item
            key={field.domkey.join('__')}
            form={form}
            fieldConfig={field}
            onChange={(...args) => {
              if (field.domkey[0] === 'selectedPubMouldId') {
                // 编辑模板
                store.changeSelectedPubMouldId(...args).then(() => {
                  form.onChange.apply(this, args);
                });
              } else if (field.domkey[0] === 'seccategory') {
                // 切换目录
                store.changeSecCategory(...args).then(() => {
                  form.onChange.apply(this, args);
                });
              } else if (field.domkey[0] === 'docPublishType'){
                // 发布类型
                store.changeDocPublishType(...args).then(() => {
                  form.onChange.apply(this, args);
                });
              } else {
                form.onChange.apply(this, args);
              }
            }}
            
            children={field.otherCom}
          />);
        });
      });
    }
    return fields;
  }
  appendBrowser = (type, datas) => {
    const {store} = this.props;
    let linkType = '';
    if (type === 'doc') {
      linkType = 37;
    } else if (type === 'workflow') {
      linkType = 152;
    } else if (type === 'customer') {
      linkType = 18;
    } else if (type === 'project') {
      linkType = 135;
    } else if (type === 'task') {
      linkType = 'prjtsk';
    } else if (type === 'upload') {
      return;
    }
    datas.forEach((item) => {
      let href = `<a onclick='openDocumentAppLink(this,${item.id},"${linkType}")' href='javascript:void(0);' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`;
      store.appendText(href);
    });
  }
}

@withRouter
@observer
export default class AddRoute extends React.Component{
  static addButton = (props)=>(
    <FloatButton
      {...props}
      offset={{x: 0, y: -53.5}}
      lowestBottom={10}
      highestTop={10}
      style={{display: 'none'}}
      className="wea-system-doc-add"
      activeClassName="wea-system-doc-add-active"
    >
      <div>
        <Icon type="plus"/>
      </div>
      <div>
        <span>{getLabel(365, '新建')}</span>
      </div>
    </FloatButton>
  )
  static Component = Add;
  
  render() {
    if (!this.props.store) return null;
    return (
      <Route
        key={`system-doc-add-page`}
        path={this.props.store.path}
        render={() => {
          return (
            <Add {...this.props}/>
          );
        }}
      />
    );
  }
}